<template>
  <div>
    <el-form ref="form" :model="form" label-width="80px" inline size="mini">
      <el-form-item label="员工名称">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="手机号码">
        <el-input v-model="form.phoneNumber"></el-input>
      </el-form-item>

      <el-form-item label="状态">
        <el-select v-model="form.status" placeholder="请选择状态">
          <el-option label="启动" value="0"></el-option>
          <el-option label="禁用" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" class="el-icon-search" @click="searchRole">查询</el-button>
        <el-button type="primary" @click="clear">清空</el-button>
        <el-button
          type="success"
          class="el-icon-folder-add"
          @click="saveOrUpdateUser('add')"
          >新增员工</el-button
        >
        <el-button type="danger" icon="el-icon-delete" @click="allDelet" :disabled='ids.length<1'>批量删除</el-button>
      </el-form-item>
    </el-form>
    <!-- 对话框 -->
    <el-dialog :title="desc" :visible.sync="dialogVisible" width="600px">
      <div>
        <el-form
          ref="userForm"
          :model="userForm"
          :rules="rules"
          inline
          size="mini"
        >
          <el-row>
            <div v-if="desc !== '提示'">
              <el-col :span="12"
                ><el-form-item label="用户名" prop="username">
                  <el-input
                    v-model="userForm.username"
                    placeholder="请输入账户名称"
                  ></el-input> </el-form-item
              ></el-col>
              <el-col :span="12" v-if="desc === '添加用户'"
                ><el-form-item label="账户密码" prop="password">
                  <el-input
                    v-model="userForm.password"
                    placeholder="请输入账户密码"
                  ></el-input> </el-form-item
              ></el-col>
              <el-col :span="12">
                <el-form-item label="关联角色" prop="sysRoleIds">
                  <el-select
                    v-model="userForm.sysRoleIds"
                    placeholder="请选择"
                    multiple
                    @remove-tag='removeTag'
                  >
                    <el-option
                      :label="item.name"
                      :value="item.id"
                      v-for="item in sysRoleList"
                      :key="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号码" prop="phoneNumber">
                  <el-input
                    v-model="userForm.phoneNumber"
                    placeholder="请输入手机号码"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户状态">
                  <el-switch
                    v-model="userForm.status"
                    active-value="0"
                    inactive-value="1"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                  >
                  </el-switch>
                </el-form-item>
              </el-col>
               <!-- <el-col :span="24">
                <el-form-item label="头像上传">
                  <el-upload
                  class="avatar-uploader"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </el-col> -->
            </div>
            <el-col :span="24" v-else>
              <el-form-item
                prop="newPassword"
                :label="`重置${userForm.username}的密码`"
              >
                <!-- <p>请输入{{ userForm.username }}的新密码</p> -->
                <el-input v-model="userForm.newPassword"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div slot="footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 列表 -->
    <el-table
      :data="userInfoList"
      style="width: 100%"
      border
      @select="selectUser"
      @select-all="selectAllUser"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column width="60" align="center" type="index" label="序号">
      </el-table-column>
      <el-table-column
        width="100"
        header-align="center"
        align="center"
        prop="username"
        label="用户名"
      >
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        prop="phoneNumber"
        label="手机号"
      >
      </el-table-column>
      <el-table-column header-align="center" align="center" label="权限列表">
        <template slot-scope="{ row }">
          <el-tag
            size="medium"
            v-for="item in row.sysRoleList"
            :key="item.id"
            >{{ item.name }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        prop="createTime"
        label="创建时间"
      >
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        prop="updateTime"
        label="更新时间"
      >
      </el-table-column>
      <el-table-column header-align="center" align="center" label="状态">
        <template slot-scope="{ row }">
          <el-switch
            :value="row.status"
            active-value="0"
            inactive-value="1"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="switchChange(row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{ row }">
          <el-button
            type="text"
            class="el-icon-edit"
            @click="saveOrUpdateUser('edit', row)"
            >修改</el-button
          >
          <el-button type="text" class="el-icon-edit" @click="resetUser(row)"
            >重置</el-button
          >
          <el-popconfirm
            @onConfirm="deleteUser(row.id)"
            confirm-button-text="好的"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="确定删除吗？"
            style="margin-left: 10px"
          >
            <el-button type="text" class="el-icon-delete" slot="reference"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
      <!-- 无数据 -->
      <template slot="empty">
        <div class="noData">
          <!--  v-show="data.length===0" -->
          <img src="@/assets/images/noData.png" />
          <p>暂无数据</p>
        </div>
      </template>
    </el-table>
    <Pagination :total="total" @pagination="handleSizeChange"></Pagination>
  </div>
</template>

<script>
import { roleList } from "@/api/system-setup/role-management";
import {
  updateUserPwd,
  userList,
  saveAndUpdate,
  updateStatus,
  deleteUser,
  grantRole,
} from "@/api/system-setup/user-management";
export default {
  data() {
    return {
      restUserName: "",
      desc: "",
      total: 0,
      dialogVisible: false,
      nowUser: {},
      form: {
        username: "",
        phoneNumber: "",
        status: "",
      },
      userForm: {
        avatar: "",
        createTime: "",
        email: "",
        id: 0,
        loginDate: "",
        newPassword: "",
        pageNum: 0,
        pageSize: 10,
        password: "",
        phoneNumber: "",
        remark: "",
        roles: "",
        status: "0",
        sysRoleIds: [],
        sysRoleList: [],
        updateTime: "",
        username: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 11,
            message: "长度在 6 到 11 个字符",
            trigger: "blur",
          },
        ],
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          {
            min: 6,
            max: 11,
            message: "长度在 6 到 11 个字符",
            trigger: "blur",
          },
        ],
        sysRoleIds: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个角色",
            trigger: "change",
          },
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号码", trigger: "change" },
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', trigger: 'change' },
        ],
      },
      selectUserId: 0,
      selectUserRole: {},
      sysRoleList: [],
      userInfoList: [],
      ids: [],
    };
  },
  created() {
    this.searchUser();
  },
  methods: {
    selectUser(selection, row) {
      let index = this.ids.indexOf(row.id);
      index === -1 ? this.ids.push(row.id) : this.ids.splice(index, 1);
    },
    selectAllUser(selection) {
      this.ids = [];
      selection.forEach((item) => {
        this.ids.push(item.id);
      });
    },
    allDelet() {
      this.$confirm("是否删除选中的用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deleteUser(this.ids).then(() => {
            this.ids = [];
          });
        })
        .catch(() => {
          this.$message("已取消");
        });
    },
    clear() {
      this.form = {
        username: "",
        phoneNumber: "",
        status: "",
      };
      this.searchUser();
    },
    async getRolesInfo() {
      let data = {
        code: "", //角色名称
        createTime: "",
        id: 0,
        name: "",
        pageNum: 1, //当前页
        pageSize: 9999, //每页条数
        remark: "", //备注
        updateTime: "",
      };
      let res = await roleList(data);
      if (res.code === 200) {
        this.sysRoleList = res.data.records;
      }
    },
    handleSizeChange(val) {
      this.userForm.pageNum = val.page;
      this.userForm.pageSize = val.limit;
      this.searchUser();
    },
    switchChange(row) {
      //console.log(row.status);
      let text = row.status === "0" ? "禁用" : "启用";
      this.$confirm(`是否${text}该用户`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let status = text === "禁用" ? "1" : "0";
          let res = await updateStatus({ id: row.id, status });
          if (res.code == 200) {
            this.msgSuccess(`${text}成功`);
            this.searchUser();
          }
        })
        .catch(() => {
          this.$message("取消");
        });
    },
    //查询
    async searchUser() {
      let res = await userList(Object.assign(this.userForm, this.form));
      if (res.code == 200) {
        this.current = res.data.userList.current;
        this.userInfoList = res.data.userList.records;
        this.total = res.data.userList.total;
      }
    },
    //添加或修改api
    async addOrUpdataUser() {
      if (this.desc === "edit") {
        let res = await grantRole({
          data: this.userForm.sysRoleIds,
          userId: this.userForm.id,
        });
        if (res.code == 200) {
          this.msgSuccess(res.msg);
        }
      }
      let res = await saveAndUpdate(this.userForm);
      if (res.code == 200) {
        this.userForm = {
          avatar: "",
          createTime: "",
          email: "",
          id: 0,
          loginDate: "",
          newPassword: "",
          pageNum: this.current,
          pageSize: 10,
          password: "",
          phoneNumber: "",
          remark: "",
          roles: "",
          status: "0",
          sysRoleIds: [],
          sysRoleList: [],
          updateTime: "",
          username: "",
        };
        this.searchUser();
      }
    },
    //查询按钮
    searchRole() {
      this.searchUser();
    },
    removeTag(e){
      let res = this.userForm.sysRoleList.filter(item=>item.id !== e)
      //console.log(res)
      this.userForm.sysRoleList  =res
    },
    //添加或新增按钮
    saveOrUpdateUser(type, row = { id: 0 }) {
      this.selectUserId = row.id;
      this.dialogVisible = true;
      this.sysRoleList.length === 0 ? this.getRolesInfo() : "";
      console.log(row);
      this.nowUser = row;
      if (type === "edit") {
        this.desc = "修改用户";
        this.userForm.sysRoleIds = [];
        this.userForm.sysRoleList.forEach((item) => row.sysRoleIds.push(item.id));
        //row.sysRoleIds = [];
        //row.sysRoleList.forEach((item) => row.sysRoleIds.push(item.id));
        this.userForm = row
        //this.userForm = JSON.parse(JSON.stringify(row));
       
      } else {
        this.desc = "添加用户";
        this.userForm = {
          avatar: "",
          createTime: "",
          email: "",
          id: 0,
          loginDate: "",
          newPassword: "",
          pageNum: this.current,
          pageSize: 10,
          password: "",
          phoneNumber: "",
          remark: "",
          roles: "",
          status: "0",
          sysRoleIds: [],
          sysRoleList: [],
        };
      }
    },
    resetUser(row) {
      this.dialogVisible = true;
      this.desc = "提示";
      this.userForm = row;
      // this.restUserName = row.username
    },
    async deleteUser(id) {
      let data;
      id instanceof Array ? (data = id) : (data = [id]);
      if (!(id instanceof Array)) {
      // } else {
        let res = await deleteUser([id]);
      }
      let res = await deleteUser(data);
      if (res.code == 200) {
         this.userInfoList.length > 1
          ? this.userForm.pageNum
          : this.userForm.pageNum--;
        this.searchUser();
      }
    },
    async confirm() {
      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          if (this.desc !== "提示") {
            this.addOrUpdataUser();
          } else {
            let res = await updateUserPwd(this.userForm);
            if (res.code == 200) {
              this.msgSuccess("修改成功");
            }
          }
          this.dialogVisible = false;
        } else {
          return false;
        }
      });
    },
    close() {
       this.userForm = {
          avatar: "",
          createTime: "",
          email: "",
          id: 0,
          loginDate: "",
          newPassword: "",
          pageNum: this.current,
          pageSize: 10,
          password: "",
          phoneNumber: "",
          remark: "",
          roles: "",
          status: "0",
          sysRoleIds: [],
          sysRoleList: [],
        };
      this.dialogVisible = false;
    },
  },
};
</script>

<style>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 50px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  </style>
